package service;

import dao.MemberDao;
import dao.impl.MemberDaoImpl;
import org.apache.commons.beanutils.BeanUtils;
import org.junit.Test;
import pojo.Member;
import pojo.MemberRole;
import util.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;

public class MemberService {

    private MemberDao memberDao = new MemberDaoImpl();

    /**
     * 展示所有会员的方法
     * @param request
     * @param response
     */
    public void listMember(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, String[]> parameterMap = request.getParameterMap();
            Member member = new Member();
            BeanUtils.populate(member, parameterMap);
            List<Member> memberList = memberDao.listMember(member);
            if (memberList == null){
                Result.response(1001, "查询失败!", response);
                return;
            }
            Result.response(0, "查询成功！", memberDao.countListMember(member), response, memberList);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }


    }

    /**
     * 软删除
     * @param request
     * @param response
     */
    public void delete(HttpServletRequest request, HttpServletResponse response) {
        String[] ids = request.getParameterValues("ids[]");
        if (ids == null){
            Result.response(1002,"参数不正确!", response);
            return;
        }
        Boolean res = false;
        // 遍历ids
        for (String id : ids) {
            res = memberDao.delete(id) > 0 ? true : false;
        }
        if (res) {
            Result.response(200, "删除成功!", response);
            return;
        }
        Result.response(1001, "删除失败!", response);
    }

    /**
     * 获取所有会员类型
     * @param request
     * @param response
     */
    public void getAllMemberRole(HttpServletRequest request, HttpServletResponse response) {
        List<MemberRole> memberRoleList = memberDao.getAllMemberRole();
        if (memberRoleList == null){
            Result.response(1001, "查找失败！", response);
        }else {
            Result.response(200,"查找成功！", response, memberRoleList);
        }

    }

    /**
     * 编辑会员
     * @param request
     * @param response
     */
    public void edit(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, String[]> parameterMap = request.getParameterMap();
            String oldMemberPassword = request.getParameter("oldMemberPassword");
            Member member = new Member();
            // 将页面上的数据写入member
            BeanUtils.populate(member, parameterMap);
            // 通过id查找到数据库中的member
            Member memberById = memberDao.findMemberById(member.getMemberId().toString());
            // 判断原密码是否输入正确
            member.setMemberPassword(MD5Util.MD55(oldMemberPassword));
            if (!MD5Util.MD55(oldMemberPassword).equals(memberById.getMemberPassword())){
                Result.response(1001, "原密码不正确！", response);
                return;
            }
            // 当修改了手机号时 判断手机号是否已经存在
            if (!member.getMemberPhone().equals(memberById.getMemberPhone())){
                if (memberDao.checkPhoneExist(member.getMemberPhone())) {
                    Result.response(1002, "该手机号已存在！", response);
                    return;
                }
            }
            String memberPassword = request.getParameter("memberPassword");
            if (!"".equals(memberPassword)&&memberPassword!=null){
                member.setMemberPassword(MD5Util.MD55(memberPassword));
            }
            member.setMemberUpdateTime(new Timestamp(System.currentTimeMillis()));
            if (memberDao.edit(member)>0) {
                LogUtil.addLog("编辑会员信息成功,会员id["+member.getMemberId()+"]", request);
                Result.response(200, "编辑成功！",response);
                return;
            }
            LogUtil.addLog("编辑会员信息失败,会员id["+member.getMemberId()+"]", request,0);
            Result.response(1001, "编辑失败!", response);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取当前编辑的会员对象
     * @param request
     * @param response
     */
    public void getEditMember(HttpServletRequest request, HttpServletResponse response) {
        String memberId = request.getParameter("memberId");
        // 验证数据
        if (!StringDataCheckUtil.check(memberId)) {
            Result.response(1001, "数据有误！", response);
            return;
        }
        Member memberById = memberDao.findMemberById(memberId);
        request.getSession().setAttribute("editMember", memberById);
    }

    /**
     * 真删除
     * @param request
     * @param response
     */
    public void realDelete(HttpServletRequest request, HttpServletResponse response) {
        String[] ids = request.getParameterValues("ids[]");
        if (ids == null){
            Result.response(1002,"参数不正确!", response);
            return;
        }
        Boolean res = false;
        // 遍历ids
        for (String id : ids) {
            res = memberDao.realDelete(id) > 0 ? true : false;
        }
        if (res) {
            Result.response(200, "删除成功!", response);
            return;
        }
        Result.response(1001, "删除失败!", response);
    }


    /**
     * 恢复会员
     * @param request
     * @param response
     */
    public void restore(HttpServletRequest request, HttpServletResponse response) {
        String restoreId = request.getParameter("restoreId");
        Boolean res = false;
        res = memberDao.restore(Integer.valueOf(restoreId)) > 0 ? true : false;
        if (res) {
            Result.response(200, "恢复成功!", response);
            return;
        }
        Result.response(1001, "恢复失败!", response);
    }

    /**
     * 根据电话号码发送验证码
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void sendCodeByMemberPhone(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String forgetMemberPhone = request.getParameter("forgetMemberPhone");
        String relCode = SendCodeUtil.sendCode(forgetMemberPhone);
        if ("".equals(relCode)&&relCode==null){
            Result.response(1001, "验证码发送失败",response);
        }
        Result.response(200, "验证码已下发，请耐心等待...",response,relCode);
    }


    /**
     * 根据验证码修改密码
     * @param request
     * @param response
     */
    public void resetPasswordByForgetWorkerPhone(HttpServletRequest request, HttpServletResponse response){
        String forgetMemberId = request.getParameter("forgetMemberId");
        String resetPassword = request.getParameter("resetPassword");
            if (memberDao.updateMemberPasswordByMemberId(forgetMemberId,MD5Util.MD55(resetPassword))<=0){
                Result.response(1001, "重置密码失败", response);
                LogUtil.addLog("重置密码失败,密码修改错误。会员id["+forgetMemberId+"]",request, 0);
            }
            Result.response(200, "重置密码成功", response);
            LogUtil.addLog("id为["+forgetMemberId+"]的会员重置密码成功。", request);
    }
}

